package com.ruoyi.common.utils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.temporal.TemporalAdjusters;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

import com.ruoyi.common.constant.Constants;
import org.apache.commons.lang3.time.DateFormatUtils;

/**
 * 时间工具类
 *
 * @author ruoyi
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils
{
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    private final static long minute = 60 * 1000;// 1分钟
    private final static long hour = 60 * minute;// 1小时
    private final static long day = 24 * hour;// 1天
    private final static long month = 31 * day;// 月
    private final static long year = 12 * month;// 年
    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate()
    {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime()
    {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow()
    {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format)
    {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date)
    {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts)
    {
        try
        {
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            return parseDate(str.toString(), parsePatterns);
        }
        catch (ParseException e)
        {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate()
    {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算相差天数
     */
    public static int differentDaysByMillisecond(Date date1, Date date2)
    {
        return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
    }

    /**
     * 计算时间差
     *
     * @param endDate 最后时间
     * @param startTime 开始时间
     * @return 时间差（天/小时/分钟）
     */
    public static String timeDistance(Date endDate, Date startTime)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - startTime.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor)
    {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor)
    {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 获取前缀+时间格式+两位随机数
     * @param prefix
     * @param rNumber
     * @return
     */
    public static String generateSerialNumber(String prefix,int rNumber){
        String dateTime = dateTimeNow();

        Random random = new Random();
        int randomNum = random.nextInt(10000);
        String serialNumber = prefix+ dateTime + String.format("%0"+rNumber+"d", randomNum);

        return serialNumber;
    }
    /**
     * 增加多少天
     * @param currentDate
     * @param rNumber
     * @return
     */
    public static Date dateAddDay(Date currentDate,int rNumber){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);
        // 在当前日期上增加7天
        calendar.add(Calendar.DAY_OF_MONTH, rNumber);
        Date newDate = calendar.getTime();
        return newDate;
    }
    /**
     * 返回文字描述的日期
     *
     * @param date
     * @return
     */
    public static String getTimeFormatText(Date date) {
        if (date == null) {
            return null;
        }
        long diff = new Date().getTime() - date.getTime();
        long r = 0;
        if (diff > year) {
            r = (diff / year);
            return r + "年前";
        }
        if (diff > month) {
            r = (diff / month);
            return r + "个月前";
        }
        if (diff > day) {
            r = (diff / day);
            return r + "天前";
        }
        if (diff > hour) {
            r = (diff / hour);
            return r + "个小时前";
        }
        if (diff > minute) {
            r = (diff / minute);
            return r + "分钟前";
        }
        return "刚刚";
    }
    // 获取指定周数的开始时间和结束时间
    public static LocalDateTime[] getWeekRange(LocalDateTime dateTime, int weeks)
    {
        LocalDateTime startOfWeek = dateTime.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)).with(LocalTime.MIDNIGHT);
        LocalDateTime endOfWeek = startOfWeek.plusWeeks(weeks).minusSeconds(1); // 下一个周一的前一秒作为结束时间
        // 如果您需要周日的午夜作为结束时间，可以改为以下代码：
        // LocalDateTime endOfWeek = startOfWeek.plusDays((long) weeks * 7 - 1).with(LocalTime.MIDNIGHT);

        return new LocalDateTime[]{startOfWeek, endOfWeek};
    }

    // 获取指定月数的开始时间和结束时间
    public static LocalDateTime[] getMonthRange(LocalDateTime dateTime, int months)
    {
        LocalDateTime startOfMonth = dateTime.withDayOfMonth(1).with(LocalTime.MIDNIGHT);
        LocalDateTime endOfMonth = startOfMonth.plusMonths(months).minusSeconds(1); // 下个月的第一天的前一秒作为结束时间
        // 如果您需要当月的最后一天的午夜作为结束时间，可以使用以下代码替代（但请注意，这可能会受到月份天数不同的影响）：
        // LocalDateTime endOfMonth = startOfMonth.plusMonths(months).withDayOfMonth(1).minusDays(1).with(LocalTime.MIDNIGHT);
        // 更准确的方法是使用TemporalAdjusters.lastDayOfMonth()：
        LocalDateTime accurateEndOfMonth = dateTime.with(TemporalAdjusters.lastDayOfMonth()).with(LocalTime.MIDNIGHT).plusMonths(months - 1);

        // 这里我们选择更准确的结束时间
        return new LocalDateTime[]{startOfMonth, accurateEndOfMonth};
    }
    /**
     * 跟进传入的字典code，解析成时间范围
     *
     * @param time
     * @return
     */
    public static LocalDateTime[] getTimes(String time)
    {
        if (StringUtils.isBlank(time)) return null;
        LocalDateTime startOfMonth = null;
        LocalDateTime endOfMonth = null;
        int number = 0;
        LocalDateTime dateTime = LocalDateTime.now();
        switch (time)
        {
            case Constants.CUSTOMER_TYPE_1001:
                //本年
                startOfMonth = dateTime.withDayOfYear(1).with(LocalTime.MIDNIGHT);
                endOfMonth = startOfMonth.plusYears(1).minusSeconds(1);
                break;
            case Constants.CUSTOMER_TYPE_1002:
                //上年
                startOfMonth = dateTime.minusYears(1).withDayOfYear(1).with(LocalTime.MIDNIGHT);
                endOfMonth = startOfMonth.plusYears(1).minusSeconds(1);
                break;
            case Constants.CUSTOMER_TYPE_1003:
                //本季度
                // 根据月份确定季度，并计算季度的第一个月份
                number = (dateTime.getMonthValue() - 1) / 3 * 3 + 1;
                // 设置季度开始日期为当季度的第一个月份的第一天
                startOfMonth = dateTime.withMonth(number).withDayOfMonth(1).with(LocalTime.MIDNIGHT);
                endOfMonth = startOfMonth.plusMonths(3).minusSeconds(1);
                break;
            case Constants.CUSTOMER_TYPE_1004:
                //上季度
                // 根据月份确定季度，并计算季度的第一个月份
                number = (dateTime.getMonthValue() - 1) / 3 * 3 + 1;
                // 设置季度开始日期为当季度的第一个月份的第一天
                startOfMonth = dateTime.withMonth(number).minusMonths(3).withDayOfMonth(1).with(LocalTime.MIDNIGHT);
                endOfMonth = startOfMonth.plusMonths(3).minusSeconds(1);
                break;
            case Constants.CUSTOMER_TYPE_1005:
                //本月
                startOfMonth = dateTime.withDayOfMonth(1).with(LocalTime.MIDNIGHT);
                endOfMonth = startOfMonth.plusMonths(1).minusSeconds(1);
                break;
            case Constants.CUSTOMER_TYPE_1006:
                //上月
                startOfMonth = dateTime.minusMonths(1).withDayOfMonth(1).with(LocalTime.MIDNIGHT);
                endOfMonth = startOfMonth.plusMonths(1).minusSeconds(1);
                break;
            case Constants.CUSTOMER_TYPE_1007:
                //本周
                startOfMonth = dateTime.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)).with(LocalTime.MIDNIGHT);
                endOfMonth = startOfMonth.plusWeeks(1).minusSeconds(1);
                break;
            case Constants.CUSTOMER_TYPE_1008:
                //上周
                startOfMonth = dateTime.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)).minusDays(7).with(LocalTime.MIDNIGHT);
                endOfMonth = startOfMonth.plusWeeks(1).minusSeconds(1);
                break;
            case Constants.CUSTOMER_TYPE_1009:
                //今天
                startOfMonth = dateTime.with(LocalTime.MIDNIGHT);
                endOfMonth = startOfMonth.plusDays(1).minusSeconds(1);
                break;
            case Constants.CUSTOMER_TYPE_1010:
                //昨天
                startOfMonth = dateTime.minusDays(1).with(LocalTime.MIDNIGHT);
                endOfMonth = startOfMonth.plusDays(1).minusSeconds(1);
                break;
            case Constants.CUSTOMER_TYPE_1011:
                //前7天
                number = 7;
                startOfMonth = dateTime.minusDays(number).with(LocalTime.MIDNIGHT);
                endOfMonth = startOfMonth.plusDays(number).minusSeconds(1);
                break;
            case Constants.CUSTOMER_TYPE_1012:
                //前30天
                number = 30;
                startOfMonth = dateTime.minusDays(number).with(LocalTime.MIDNIGHT);
                endOfMonth = startOfMonth.plusDays(number).minusSeconds(1);
                break;
            case Constants.CUSTOMER_TYPE_1013:
                //前60天
                number = 60;
                startOfMonth = dateTime.minusDays(number).with(LocalTime.MIDNIGHT);
                endOfMonth = startOfMonth.plusDays(number).minusSeconds(1);
                break;
            case Constants.CUSTOMER_TYPE_1014:
                //前90天
                number = 90;
                startOfMonth = dateTime.minusDays(number).with(LocalTime.MIDNIGHT);
                endOfMonth = startOfMonth.plusDays(number).minusSeconds(1);
                break;
            default:
                return null;
        }
        return new LocalDateTime[]{startOfMonth, endOfMonth};
    }
}
